<template>
  <div class="min-h-screen grid place-items-center bg-bg">
    <div class="card w-full max-w-md">
      <div class="text-center mb-4">
        <div class="text-3xl font-bold text-text mb-1">宝宝护理日记</div>
        <div class="text-sm text-gray-500">登录 / 注册</div>
      </div>

          <form @submit.prevent="onSubmit" class="space-y-3">
            <input v-model="account" class="input" placeholder="手机号/邮箱" />
            <input v-model="password" class="input" type="password" placeholder="密码" />
            <div class="flex gap-2">
              <input v-model="captcha" class="input flex-1" placeholder="图形验证码" maxlength="4" />
              <div class="captcha-container">
                <img 
                  v-if="captchaImage" 
                  :src="captchaImage" 
                  alt="验证码" 
                  class="captcha-image cursor-pointer" 
                  @click="refreshCaptcha"
                  title="点击刷新验证码"
                />
                <div v-else class="captcha-placeholder" @click="getCaptcha">
                  {{ captchaLoading ? '加载中...' : '点击获取验证码' }}
                </div>
              </div>
            </div>
            <button class="btn-primary w-full" type="submit" :disabled="loading">
              {{ loading ? '处理中...' : (isRegister ? '注册' : '登录') }}
            </button>
        <button type="button" class="btn-accent w-full" @click="goRegister" v-if="!isRegister">
          注册
        </button>
        <button type="button" class="btn-accent w-full" @click="isRegister = false" v-if="isRegister">
          返回登录
        </button>
      </form>

          <div class="flex justify-between items-center mt-3 text-sm">
            <a class="text-secondary" href="#">忘记密码？</a>
          </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';
import { API_CONFIG } from '../services/api';

// 临时解决方案：直接定义函数
async function login(payload: { account: string; password: string }) {
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/auth/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  const data = await resp.json();
  localStorage.setItem('auth_token', data.token);
  return data;
}

async function register(payload: { account: string; password: string; nickname?: string }) {
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/auth/register`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  const data = await resp.json();
  // 注册成功后不设置token，需要用户重新登录
  return data;
}

const router = useRouter();
const userStore = useUserStore();
const account = ref('');
const password = ref('');
const captcha = ref('');
const captchaImage = ref('');
const captchaToken = ref('');
const loading = ref(false);
const captchaLoading = ref(false);
const isRegister = ref(false);


// 获取图形验证码
async function getCaptcha() {
  try {
    captchaLoading.value = true;
    const resp = await fetch(`${API_CONFIG.BASE_URL}/api/auth/captcha/image`, {
      method: 'GET'
    });

    if (!resp.ok) {
      const errorText = await resp.text();
      throw new Error(`HTTP ${resp.status}: ${errorText}`);
    }

    const result = await resp.json();
    captchaImage.value = result.image; // Base64图片数据
    captchaToken.value = result.token; // 验证码token
    captcha.value = ''; // 清空输入框
  } catch (error) {
    console.error('获取验证码失败:', error);
    alert('获取验证码失败，请重试');
  } finally {
    captchaLoading.value = false;
  }
}

// 刷新验证码
function refreshCaptcha() {
  getCaptcha();
}

// 处理认证错误
async function handleAuthError(error) {
  try {
    let errorType = '';
    let errorMessage = '';
    
    // 检查是否是HTTP错误响应
    if (error.response) {
      try {
        const errorResponse = await error.response.json();
        errorType = errorResponse.errorType || '';
        errorMessage = errorResponse.error || errorResponse.message || '';
      } catch (parseError) {
        // 如果无法解析JSON，使用HTTP状态码判断
        errorMessage = `HTTP ${error.response.status}: ${error.response.statusText}`;
      }
    } else {
      // 网络错误或其他错误
      errorMessage = error.message || '网络错误，请检查网络连接';
    }
    
    switch (errorType) {
      case 'CAPTCHA_INVALID':
        // 验证码错误：刷新验证码图片
        alert('验证码错误或已过期，请重新输入');
        await getCaptcha(); // 自动刷新验证码
        break;
        
      case 'CAPTCHA_REQUIRED':
        // 验证码为空
        alert('请输入验证码');
        break;
        
      case 'LOGIN_FAILED':
        // 账号密码错误：不清除验证码
        alert('账号或密码错误');
        break;
        
      case 'REGISTER_FAILED':
        // 注册失败（如账号已存在）
        alert(errorMessage || '注册失败，请重试');
        break;
        
      default:
        // 其他错误
        alert(errorMessage || '操作失败，请重试');
        break;
    }
  } catch (handleError) {
    // 如果处理错误时出现异常，使用默认错误处理
    console.error('处理错误时出现异常:', handleError);
    alert('操作失败，请重试');
  }
}

async function onSubmit() {
  if (!account.value || !password.value || !captcha.value) {
    alert('请填写完整信息');
    return;
  }
  
  try {
    loading.value = true;
    if (isRegister.value) {
      const payload = {
        account: account.value,
        password: password.value,
        nickname: '用户',
        captcha: captcha.value,
        captchaToken: captchaToken.value
      };
      await register(payload);
      alert('注册成功！请登录');
      isRegister.value = false; // 切换到登录模式
      captcha.value = ''; // 清空验证码
      captchaImage.value = ''; // 清空验证码图片
      captchaToken.value = ''; // 清空验证码token
      return;
    } else {
      const payload = {
        account: account.value,
        password: password.value,
        captcha: captcha.value,
        captchaToken: captchaToken.value
      };
      const response = await login(payload);
      userStore.setUser(response.user);
      router.push('/');
    }
  } catch (error) {
    console.error('认证失败:', error);
    handleAuthError(error);
  } finally {
    loading.value = false;
  }
}

function goRegister() {
  isRegister.value = true;
}

// 页面加载时自动获取验证码
onMounted(() => {
  getCaptcha();
});

</script>

<style scoped>
.captcha-container {
  width: 120px;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: opacity 0.2s;
}

.captcha-image:hover {
  opacity: 0.8;
}

.captcha-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #666;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.captcha-placeholder:hover {
  background-color: #e5e5e5;
}
</style>
